package org.pisces.wechat.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.pisces.wechat.commons.WechatConstants;
import org.pisces.wechat.commons.utils.HttpClientUtils;
import org.pisces.wechat.commons.utils.SignUtil;
import org.pisces.wechat.service.api.IWechatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("/wechat")
public class WechatController {
	
	@Autowired
	private IWechatService wechatService;
	
	@Value("${wechat.app.id}")
	private String appId;
	
	@Value("${wechat.app.secret}")
	private String secret;
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@GetMapping("/advanced")
	public void get(HttpServletRequest request, HttpServletResponse response) {
		logger.info("get验证");
		// 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
			if (SignUtil.checkSignature(signature, timestamp, nonce)) {
				out.print(echostr);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.close();
			out = null;
		}
	}
	
	
	@PostMapping("/advanced")
	public void post(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String msgSignature = request.getParameter("msg_signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		String encyptMsg = IOUtils.toString(request.getInputStream(),"utf-8");
		String outMessage = wechatService.advanced(msgSignature,timestamp,nonce,encyptMsg);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml");
		response.getWriter().write(outMessage);
		
	}
	
	@GetMapping("redirect")
	public String redirect() throws UnsupportedEncodingException{
		System.out.println(appId);
		String resultUrl = URLEncoder.encode("http://17939a5d39.imwork.net/wechat/userinfo/","utf-8");
		StringBuilder sb = new StringBuilder();
		sb.append(WechatConstants.WECHAT_OPEN_URL).append("/connect/oauth2/authorize").append("?appid=").append(appId).append("&redirect_uri=")
				.append(resultUrl).append("&response_type=code&scope=snsapi_base");
		return "redirect:"+sb.toString();
	}
	
	
	@GetMapping("userinfo")
	public String userInfo(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter("code");
		JSONObject result = getAccessToken(code);
		logger.info("result:{}",result.toJSONString());
		return result.getString("openid");
	}
	
	/**
	 * 用户token
	 * 
	 * @since 1.0
	 * @param code
	 * @return <br>
	 * 		<b>作者： @author 宋旋 <xuan.song@utsoft.cn></b> <br>
	 * 		创建时间：2017年8月7日 下午7:58:20
	 */
	private JSONObject getAccessToken(String code) {
		String urls = WechatConstants.WECHAT_API_URL + "/sns/oauth2/access_token";
		Map<String, String> map = new HashMap<String, String>();
		map.put("appid", appId); // 公众号的唯一标识
		map.put("secret", secret); // 公众号的appsecret
		map.put("code", code); // 填写第一步获取的code参数
		map.put("grant_type", "authorization_code"); // 填写为authorization_code
		String doPost = null;
		try {
			doPost = HttpClientUtils.postParameters(urls, map);
		} catch (Exception e) {
			return new JSONObject();
		}
		JSONObject json = JSONObject.parseObject(doPost);
		logger.info(json.toString());
		return json;
	}
	
	
}
